/**
 * @author	huangfeng
 * @class	Ext.ux.ComboImage
 * 显示图片的combo
 */
Ext.ux.ComboImage = Ext.extend(Ext.form.ComboBox ,{
	defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
	defaultLabelCreate: {tag:"div",id:'imageLabel',cls:"imageLabel"},
	imageLabel:{},
	/**
	 * 初始化组件
	 */
	initComponent : function(){
        Ext.ux.ComboImage.superclass.initComponent.call(this);
        this.addEvents(
            /**
             * @event expand
             * Fires when the dropdown list is expanded
             * @param {Ext.form.ComboBox} combo This combo box
             */
            'expand',
            /**
             * @event collapse
             * Fires when the dropdown list is collapsed
             * @param {Ext.form.ComboBox} combo This combo box
             */
            'collapse',
            /**
             * @event beforeselect
             * Fires before a list item is selected. Return false to cancel the selection.
             * @param {Ext.form.ComboBox} combo This combo box
             * @param {Ext.data.Record} record The data record returned from the underlying store
             * @param {Number} index The index of the selected item in the dropdown list
             */
            'beforeselect',
            /**
             * @event select
             * Fires when a list item is selected
             * @param {Ext.form.ComboBox} combo This combo box
             * @param {Ext.data.Record} record The data record returned from the underlying store
             * @param {Number} index The index of the selected item in the dropdown list
             */
            'select',
            /**
             * @event beforequery
             * Fires before all queries are processed. Return false to cancel the query or set the queryEvent's
             * cancel property to true.
             * @param {Object} queryEvent An object that has these properties:<ul>
             * <li><code>combo</code> : Ext.form.ComboBox <div class="sub-desc">This combo box</div></li>
             * <li><code>query</code> : String <div class="sub-desc">The query</div></li>
             * <li><code>forceAll</code> : Boolean <div class="sub-desc">True to force "all" query</div></li>
             * <li><code>cancel</code> : Boolean <div class="sub-desc">Set to true to cancel the query</div></li>
             * </ul>
             */
            'beforequery'
        );

        if(this.transform){
            this.allowDomMove = false;
            var s = Ext.getDom(this.transform);
            if(!this.hiddenName){
                this.hiddenName = s.name;
            }
            if(!this.store){
                this.mode = 'local';
                var d = [], opts = s.options;
                for(var i = 0, len = opts.length;i < len; i++){
                    var o = opts[i];
                    var value = (Ext.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
                    if(o.selected) {
                        this.value = value;
                    }
                    d.push([value, o.text]);
                }
                this.store = new Ext.data.SimpleStore({
                    'id': 0,
                    fields: ['value', 'text'],
                    data : d
                });

                this.valueField = 'value';
                this.displayField = 'text';
            }
            s.name = Ext.id(); // wipe out the name in case somewhere else they have a reference
            if(!this.lazyRender){
                this.target = true;
                this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
                
               
                
                Ext.removeNode(s); // remove it
                this.render(this.el.parentNode);
            }else{
                Ext.removeNode(s); // remove it
            }
        }
        //auto-configure store from local array data
        else if(Ext.isArray(this.store)){
			if (Ext.isArray(this.store[0])){
				this.store = new Ext.data.SimpleStore({
				    fields: ['value','text'],
				    data: this.store
				});
		        this.valueField = 'value';
			}else{
				this.store = new Ext.data.SimpleStore({
				    fields: ['text'],
				    data: this.store,
				    expandData: true
				});
		        this.valueField = 'text';
			}
			this.displayField = 'text';
			this.mode = 'local';
		}else{
			this.valueField = 'url';
		}
		
        this.selectedIndex = -1;
        if(this.mode == 'local'){
            if(this.initialConfig.queryDelay === undefined){
                this.queryDelay = 10;
            }
            if(this.initialConfig.minChars === undefined){
                this.minChars = 0;
            }
        }
    },
    /**
     * 显示控件函数
     * @param	ct			容器对象
     * @param	position	容器的位置
     */
    onRender : function(ct, position){  	
        Ext.ux.ComboImage.superclass.onRender.call(this, ct, position);
        this.imageLabel=Ext.DomHelper.insertBefore(this.el,this.defaultLabelCreate);   
    },
    /**
     * 选择控件
     * @param	record	选中的item的数据
     * @param	index	选中的item的索引值
     * @param	e		事件对象
     */
    onSelect : function(record, index,e){
		//把图片放在输入框的末尾
    	Ext.ux.ComboImage.superclass.onSelect.call(this,record,index); 
    	this.setImage(record.data.url);
    },
    /**
     * 重置
     */
    reset : function(){
        Ext.ux.ComboImage.superclass.reset.call(this);
        Ext.DomHelper.overwrite(this.imageLabel,'');
    },
    /**
     * 设置值
     */
    setValue:function(v){
    	Ext.ux.ComboImage.superclass.setValue.call(this,v);   	
    	this.setImage(v);
    },
    /**
     * 设置图片
     * @param	url	图片地址
     */
    setImage:function(url){
    	if(url==''){
    		return ;
    	}
    	url=url.replace('..','');
    	var element=Ext.select('img[src*="'+url+'"]');
    	if(element.elements.length!=0){
    		this.imageLabel.style.left=this.el.getWidth()-element.elements[0].width;
    		Ext.DomHelper.overwrite(this.imageLabel,{tag:'img',src:element.elements[0].src});
    	}
    	  
    },
    /**
     * 初始化下拉显示内容
     */
	initList:function(){
		if(!this.list){
            var cls = 'x-combo-list';

            this.list = new Ext.Layer({
                shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
            });

            var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
            this.list.setWidth(lw);
            this.list.swallowEvent('mousewheel');
            this.assetHeight = 0;

            if(this.title){
                this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
                this.assetHeight += this.header.getHeight();
            }

            this.innerList = this.list.createChild({cls:cls+'-inner images-view'});
            //this.innerList.on('mouseover', this.onViewOver, this);
            //this.innerList.on('mousemove', this.onViewMove, this);
            this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));

            if(this.pageSize){
                this.footer = this.list.createChild({cls:cls+'-ft'});
                this.pageTb = new Ext.PagingToolbar({
                    store:this.store,
                    pageSize: this.pageSize,
                    renderTo:this.footer
                });
                this.assetHeight += this.footer.getHeight();
            }

            
            this.tpl = new Ext.XTemplate(
				'<tpl for=".">',
		            '<div class="thumb-wrap" id="{name}">',
				    '<div class="thumb"><img src="{url}" title="{name}"></div>',
				    '<span class="x-editable">{shortName}</span></div>',
		        '</tpl>',
		        '<div class="x-clear"></div>'
			);
			
			this.view =new Ext.DataView({
					applyTo:this.innerList,
		            store: this.store,
		            tpl: this.tpl,
		            autoHeight:true,
		            multiSelect: true,
		            overClass:'x-view-over',
		            itemSelector:'div.thumb-wrap',
		            emptyText: 'No images to display',
					
		            prepareData: function(data){
		                data.shortName = Ext.util.Format.ellipsis(data.name, 15);
		                return data;
		            },
		            
		            listeners: {
		            	click :{
		            		fn: function(dv,index,node){
		            			var data=dv.getRecord(node);
		            			//panel.setTitle('图片选择窗(您选择了'+data.data.name+')');
		            		}
		            	},
		            	dblclick : {
		            		fn: function(dv,index,node){
		            			
		            		}
		            	}
		            }
		        });

            this.view.on('click', this.onViewClick, this);
            this.view.on('dblclick',this.onViewDblClick,this)
			
            this.bindStore(this.store, true);

            if(this.resizable){
                this.resizer = new Ext.Resizable(this.list,  {
                   pinned:true, handles:'se'
                });
                this.resizer.on('resize', function(r, w, h){
                    this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
                    this.listWidth = w;
                    this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
                    this.restrictHeight();
                }, this);
                this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
            }
        }
	}
})
Ext.reg('comboImage', Ext.ux.ComboImage);